/******************************************************************
 * Copyright @ 2023 广州牛师帮科技文化有限公司. All rights reserverd.
 * @file   src\pages\main\useNavMenu.ts
 * @author 朱剑豪
 * @date   2023/02/02 13:25
 * @desc   左侧导航菜单的逻辑封装
 ******************************************************************/

import { useArrStorage } from "@nsb/common-tools/dist/hooks/useArrayStorage";
import { useBooleanStorage } from "@nsb/common-tools/dist/hooks/useBooleanStorage";
import { Dispatch, SetStateAction, useCallback } from "react";

export namespace NavMenu {
  export interface IUseResult {
    /**
     * 处于展开状态的菜单key的数组
     */
    openKeys: string[] | null

    /**
     * 设置 处于展开状态的菜单key的数组
     */
    setOpenKeys: Dispatch<SetStateAction<string[] | null>>

    /**
     * 当前被选择的菜单条目的key
     */
    selectedKey: string

    /**
     * 选择某个菜单条目
     * @param key 菜单条目的key
     */
    select: (key: string) => void

    /**
     * 总菜单是否被展开
     */
    collapsed: boolean | null

    /**
     * 展开/收起菜单
     */
    setCollapsed: Dispatch<SetStateAction<boolean | null>>


    /**
     * 展开/收起菜单
     */
    toggleCollapsed: () => void

    /**
     * 收起后的宽度
     */
    collapsedWidth: number | undefined;
  }
  export interface IUseOpts<T extends string = string> {
    navigate: (key: T | string) => void;
    defaultValue: T[];
  }
  export function use<T extends string = string>(selectedKey: T, opts: IUseOpts<T>): IUseResult {
    const { navigate, defaultValue } = opts
    const [collapsed, setCollapsed] = useBooleanStorage("local", "nav_menu_collapsed", false)
    const [openKeys, setOpenKeys] = useArrStorage<string>("local", "open_nav_menu_keys", {
      defaultValue
    })
    const select = useCallback((key: T | string) => navigate(key), [navigate])

    return {
      openKeys, setOpenKeys,
      selectedKey, select,
      collapsed, setCollapsed,
      toggleCollapsed: () => setCollapsed(!collapsed),
      collapsedWidth: 58,
    }
  }
}
